//
//  MeImportCode.m
//  OC_Poj_demo
//
//  Created by weixin on 2018/7/20.
//  Copyright © 2018年 weixn. All rights reserved.
//

#import "MeImportCode.h"
#import "OKGetCodeBtn.h"
#import "NumberKeyboard.h"
#import "MeVC.h"
#import "WLUnitField.h"
#import "MyHelpCentre.h"
#import <UMPush/UMessage.h>
#import "MyHelpCentreWebVC.h"
#import "LoginSetPasswordView.h"

#import "WLUnitField.h"//第三方验证码

@interface MeImportCode ()<WLUnitFieldDelegate>

@property (nonatomic,strong)OKGetCodeBtn *codeBtn;

@property (weak, nonatomic) IBOutlet UIButton *JoinZITHER;

//@property (nonatomic,strong)NumberKeyboard * KB;//键盘UI
@property (weak, nonatomic) IBOutlet UILabel *lab;

@property (weak, nonatomic) IBOutlet UIButton *btn;

@property (nonatomic,strong)NSMutableArray * arrM;//存验证码

@property (nonatomic,strong)BaseLab *redTipe;//报错提示

@property (nonatomic,strong)WLUnitField * unitField;


@end

@implementation MeImportCode

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self setNav];
    
    [self setUI];
    
    [self.view addSubview:self.unitField];
    
    self.JoinZITHER.alpha = 0.4;
    /** 底部线条 */
    for (int i = 0; i<4; i++) {
        
        CGFloat width = (kScreenW-20-120)/4;
        BaseView *viewLine = [[BaseView alloc]initWithFrame:CGRectMake(20+(width+30+5)*i, 200, width, 1)];
        viewLine.backgroundColor = [UIColor colorWithHex:@"eeeeee"];
        [self.view addSubview:viewLine];
    }
    
    [self.view addSubview:self.redTipe];
    [self.redTipe mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(205);
        make.left.equalTo(self.view).offset(20);
    }];
    
    [self.unitField becomeFirstResponder];

    
}

-(WLUnitField *)unitField{
    if (!_unitField) {
        _unitField = [[WLUnitField alloc]initWithFrame:CGRectMake(10, 140, kScreenW-20, 50)];
        _unitField.backgroundColor = [UIColor randomColor];
        _unitField.delegate = self;
        _unitField.keyboardType = UIKeyboardTypeNumberPad;
        _unitField.unitSpace = 30;
        _unitField.textFont = [UIFont fontWithName:@"PingFang-SC-Regular" size:28];
//        [_unitField borderForColor:[UIColor colorWithHex:@"eeeeee"] borderWidth:1 borderType:UIBorderSideTypeBottom];
        _unitField.borderWidth = 0;
//        _unitField
//        _unitField.text = @"";
        

    }
    return _unitField;
}

- (BOOL)unitField:(WLUnitField *)uniField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    self.redTipe.hidden = YES;
    NSString *text = nil;
    if (range.location >= uniField.text.length) {
        text = [uniField.text stringByAppendingString:string];
    } else {
        text = [uniField.text stringByReplacingCharactersInRange:range withString:string];
    }
    if (text.length == 4) {
        self.JoinZITHER.alpha = 1;
    }else{
        self.JoinZITHER.alpha = 0.4;
    }
    NSLog(@"******>%@", text);
    
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view.window endEditing:YES];
}

-(void)setNav{
    [self.baseNavigationView setHiddenNav:NO VC:self];
    /* TODO: ================= 导航栏V4样式 =================*/
    [self.baseNavigationView NavigationBarStyle:1];
    self.baseNavigationView.navViewStyle.title.text = @"输入验证码";
    self.baseNavigationView.leftButton1.hidden = YES;
    self.baseNavigationView.navViewStyle.isShowShadow = NO;
    self.baseNavigationView.bottomLineView.hidden = YES;
    
    
    
    //登录或注册
//    [self.baseNavigationView setBackgroundColor:[UIColor clearColor]];
//    self.baseNavigationViexw.bottomLineView.backgroundColor = [UIColor clearColor];
//    [UIColor setDefaulGradiennBackgroundColors:self.view];
//    /* TODO: ================= 导航栏箭头颜色 =================*/
//    self.baseNavigationView.leftButton1.hidden = YES;
//
//    BaseBtn *btn = [[BaseBtn alloc]initializeFrame:CGRectMake(20, 40, 30, 30) NormalText:nil NormalTextColor:nil SeleText:nil NormalImage:@"common_back_white" SeleImage:nil SeleTextColor:nil font:nil isBold:nil];
//    @weakify(self);
//    [[btn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
//        @strongify(self);
//        [self.navigationController popViewControllerAnimated:YES];
//    }];
//
//    [self.view addSubview:btn];
    
    
    
}

-(void)setUI{

    self.lab.text = @"注册即同意";
    
    [self.btn setTitleColor:baseColorTheme forState:UIControlStateNormal];
    [self.btn setTitle:@"《免责条款》" forState:UIControlStateNormal];
    self.btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    /** 按钮点击案例 */
    @weakify(self);
    [[self.btn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        MyHelpCentreWebVC *vc = [[MyHelpCentreWebVC alloc]init];
        
        NSString *urlString = [NSString stringWithFormat:@"%@/#/faq/clause?name=%@",RootUrlWeb,RootProjectName];
//        vc.url = [NSString stringWithFormat:@"%@/#/faq/clause",RootUrlWeb];
//        vc.url = [vc.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)urlString,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL,kCFStringEncodingUTF8));
        
        vc.url = encodedString;

        vc.title1 = @"免责条款";
        
        [self.navigationController pushViewController:vc animated:YES];

    }];
   

    
    [self.JoinZITHER setTitleColor:baseColorTheme forState:UIControlStateNormal];
    [self.JoinZITHER setBorderWithColor:baseColorTheme width:1];
    [self.JoinZITHER setCornerRadiusWithRadius:4 isMasks:YES];
    
    QMUILabel *leb = [[QMUILabel alloc]initWithFrame:CGRectMake(20,80, 300, 40)];
    leb.text = @"输入收到的验证码";
    leb.font = [UIFont systemFontOfSize:25];
    leb.textColor = [UIColor whiteColor];
    [self.view addSubview:leb];
    
    [self.baseNavigationView addSubview:self.codeBtn];
    [self.codeBtn timeFailBeginFrom:45];

    [self.codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.baseNavigationView.navViewStyle.title.mas_centerY).offset(0);
        make.right.equalTo(self.view).offset(-10);
        
    }];
    
    
//    for (int i = 0; i<4; i++) {
//        CGFloat btnW = (kScreenW -24*5)/4.0;
//        QMUIButton *btn = [[QMUIButton alloc]initWithFrame:CGRectMake(24+(24+btnW)*i, 144, btnW, btnW)];
//        btn.tag = 100+i;
//        btn.titleLabel.font = [UIFont systemFontOfSize:btnW*0.4];
//        btn.backgroundColor  = [UIColor clearColor];
//        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        [btn setBorderWithColor:baseColorLight width:2];
//        [btn setCornerRadiusWithRadius:btnW*0.2 isMasks:YES];
//        [self.view addSubview:btn];
//    }
   
//    [self.view addSubview:self.KB];
    
}


- (IBAction)Back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)PushMeVC:(id)sender {

    if (self.unitField.text.length == 4) {
        
        @weakify(self);
        
        [[AccountService loadLoginForPassword:self.phoneNumber credential:self.unitField.text authMethod:@"SMS_CODE" reponseObjctClass:[UserInfoManager class]]subscribeNext:^(ResponseData * x) {
            
            if (x.success) {
                [kUSER_INFO_MANAGER saveCookie];
                ResponseData *data = x;
                UserInfoManager *model = [[UserInfoManager alloc]init];

                [model setUserInfoWithNSDictionary: data.responseRawData[@"data"]];
                
                model.token = [NSString stringWithFormat:@"Bearer %@",model.token];
                [kUSER_INFO_MANAGER setUserInfoWithModel:model];
                [kUSER_INFO_MANAGER MyList];
                //                UserInfoManager *mdoel = [UserInfoManager defaultManager];
                //                [self.navigationController pushViewController:[[MeVC alloc]init] animated:YES];
                [self.navigationController popToRootViewControllerAnimated:YES];
                //绑定别名
                [UMessage addAlias:model.userId type:@"userId" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
                    NSLog(@"");
                }];
                
                if (![data.responseRawData[@"data"][@"password"] isEqualToString:@"yes password"]) {
                    LoginSetPasswordView *cc = [[LoginSetPasswordView alloc]initWithFrame:CGRectMake(0,0, kScreenW, kScreenH)];
                    cc.nav = self.navigationController;
                    [cc show];
                }
            }else{
                [Tools showTips:x.errorInfo];
            }
        }];
        
//        [[AccountService loadLogin:self.phoneNumber phoneCode:self.unitField.text reponseObjctClass:[UserInfoManager class]]subscribeNext:^(ResponseData* x) {
//            NSLog(@"================后台响应回掉验证码====================");
//            @strongify(self);
//            if (x.success) {

//
//
//            }else{
//                 [Tools showTips:x.errorInfo];
//            }
//
//        }];
  
    }else{

        self.redTipe.hidden = NO;
        self.redTipe.text = @"验证码长度错误";
    }
}

//-(NumberKeyboard *)KB{
//    if (!_KB) {
//        _KB = [[NumberKeyboard alloc]initWithFrame:CGRectMake(0, kScreenH-240, kScreenW, 240)];
//        __weak __typeof(self)weakSelf = self;
//        [_KB setBtnBlock:^(NSInteger index) {
//            NSLog(@"%ld",index);
//
//            if (index==12) {
//                if (weakSelf.arrM.count!=0) {
//                    //删除
//                    QMUIButton * btn = (QMUIButton*)[weakSelf.view viewWithTag:weakSelf.arrM.count+99];
//                    [btn setTitle:@"" forState:UIControlStateNormal];
//                    [btn setBorderWithColor:baseColorLight width:2];
//
//                    [weakSelf.arrM  removeLastObject];
//                    return ;
//                }
//            }else{
//                if (weakSelf.arrM.count <4) {
//                    if (index == 11) {
//                        QMUIButton * btn = (QMUIButton*)[weakSelf.view viewWithTag:weakSelf.arrM.count+100];
//                        [btn setTitle:@"0" forState:UIControlStateNormal];
//                        [btn setBorderWithColor:[UIColor whiteColor] width:3];
//
//                        [weakSelf.arrM addObject:@"0"];
//                    }else if (index == 10){
//
//                    }else{
//                        QMUIButton * btn = (QMUIButton*)[weakSelf.view viewWithTag:weakSelf.arrM.count+100];
//                        [btn setTitle:[NSString stringWithFormat:@"%ld",index] forState:UIControlStateNormal];
//                        [btn setBorderWithColor:[UIColor whiteColor] width:3];
//
//                        [weakSelf.arrM addObject:[NSString stringWithFormat:@"%ld",index]];
//                    }
//              }
//            }
//
//
//
//
//
//            /* FIXME: ================= 删除验证码 再添加数据有时候会突然空一位 ================= */
//
//            if (weakSelf.arrM.count <4) {
//
//                if (index !=10) {
//                    if (index==12) {
//
//                    }else{
//
//                    }
//                }
//            }
//
//
//
//
//
//
//
//        }];
//    }
//    return _KB;
//}

-(NSMutableArray *)arrM{
    if (!_arrM) {
        _arrM = [[NSMutableArray alloc]init];
    }
    return _arrM;
}


-(BaseLab *)redTipe{
    if (!_redTipe) {
        _redTipe = [[BaseLab alloc]initializeFrame:CGRectMake(0, 0, 1, 1) text:@"输入手机号错误" font:12 textColor:[UIColor colorWithHex:@"FF6F6F"] isBold:NO numberOfLines:0];
        _redTipe.font = [UIFont fontWithName:@"PingFangSC-Medium" size:12];
        _redTipe.hidden = YES;
    }
    return _redTipe;
}

-(OKGetCodeBtn *)codeBtn{
    if (!_codeBtn) {
        _codeBtn = [[OKGetCodeBtn alloc]initWithFrame:CGRectMake(kScreenW-100, 0, 100, 40)];
//        _codeBtn.backgroundColor = [UIColor redColor];
        [_codeBtn setTitle:@"重新获取 45S" forState:UIControlStateNormal];
        _codeBtn.strTime = @"重新获取";
        _codeBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15];

        [_codeBtn setTitleColor:[UIColor colorWithHex:@"999999"] forState:UIControlStateNormal];
        @weakify(self);
        [[_codeBtn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [[AccountService loadSendSms:self.phoneNumber]subscribeNext:^(ResponseData* x) {
                @strongify(self);
                if (x.success) {
                    [self.codeBtn timeFailBeginFrom:45];
                    self.codeBtn.alpha = 0.4;
                    [self.codeBtn setTitle:@"重新获取 45S" forState:UIControlStateNormal];
                    [self.codeBtn setTitleColor:[UIColor colorWithHex:@"999999"] forState:UIControlStateNormal];
                }else{
                     [Tools showTips:x.errorInfo];
                }
                
            }];
        }];
        
    }
    return _codeBtn;
}

-(void)dealloc{
    if (self.codeBtn.timer) {
        [self.codeBtn.timer invalidate];
        self.codeBtn.timer = nil;
    }
}
@end
